package com.bootdo.system.controller;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.ui.Model;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.multipart.MultipartFile;

import com.bootdo.system.domain.CollectionDO;
import com.bootdo.system.domain.CompanyDO;
import com.bootdo.system.domain.CompanyPictureDO;
import com.bootdo.system.domain.WechatPicDO;
import com.bootdo.system.domain.UserDO;
import com.bootdo.system.domain.WechatDO;
import com.bootdo.system.service.AdvertisingService;
import com.bootdo.system.service.CollectionService;
import com.bootdo.system.service.ManageService;
import com.bootdo.system.service.MerchantService;
import com.bootdo.system.service.MiniappDetailsService;
import com.bootdo.system.service.OperatorService;
import com.bootdo.system.service.WechatPicService;
import com.bootdo.system.service.WechatService;
import com.bootdo.common.config.BootdoConfig;
import com.bootdo.common.utils.FileUtil;
import com.bootdo.common.utils.OssUtil;
import com.bootdo.common.utils.PageUtils;
import com.bootdo.common.utils.Query;
import com.bootdo.common.utils.R;

/**
 * 
 * @ClassName: WechatController
 * @Description: TODO(移动端小程序模板)
 * @author lzy
 * @date 2018年6月6日
 *
 */
@Controller
@RequestMapping("/system/wechat")
public class WechatController {
	@Autowired
	private WechatService wechatService;
	@Autowired
	private WechatPicService picService;
	@Autowired
	private CollectionService collectionService;
	@Autowired
	private MiniappDetailsService miniappDetailsService;// 小程序
	@Autowired
	private AdvertisingService advertisingService;// 广告合作
	@Autowired
	private ManageService manageService;// 合作经营
	@Autowired
	private OperatorService operatorService;// 运营商
	@Autowired
	private MerchantService merchantService;// 商家

	@GetMapping()
	@RequiresPermissions("system:wechat:wechat")
	String Wechat() {
		return "system/wechat/wechat";
	}

	@ResponseBody
	@GetMapping("/list")
	public PageUtils list(@RequestParam Map<String, Object> params) {
		// 查询列表数据
		Query query = new Query(params);
		List<WechatDO> wechatList = wechatService.list(query);
		int total = wechatService.count(query);
		PageUtils pageUtils = new PageUtils(wechatList, total);
		return pageUtils;
	}

	@GetMapping("/add")
	String add() {
		return "system/wechat/add";
	}

	@GetMapping("/upload/{id}")
	String upload(@PathVariable("id") Integer id, Model model) {
		WechatDO wechat = wechatService.get(id);
		model.addAttribute("name", wechat.getName());
		model.addAttribute("id", wechat.getId());
		return "system/wechat/upload";
	}

	@GetMapping("/edit/{id}")
	String edit(@PathVariable("id") Integer id, Model model) {
		WechatDO wechat = wechatService.get(id);
		model.addAttribute("wechat", wechat);
		return "system/wechat/edit";
	}
	
	
	@GetMapping("/logo/{id}")
	String editLogo1(@PathVariable("id") Integer id, Model model) {
		WechatDO wechat = wechatService.get(id);
		model.addAttribute("logoUrl",wechat.getUrl());
		model.addAttribute("id",id);
		
		return "system/wechat/logo";
	}
	
	/**
	 * 小程序模板主图修改
	 */
	@ResponseBody
	@PostMapping("/editLogo")
	public R saveLogo(@RequestParam("img") MultipartFile img,Integer id){
		WechatDO wechatDO = wechatService.get(id);
		String imgUrl=wechatDO.getUrl().substring(45, 62);
		OssUtil.deleteBucketInfo(imgUrl);
		String url =null;
		try {
			url = OssUtil.fileUpload(img);
			WechatDO wechat = new WechatDO();
			wechat.setId(id);
			wechat.setUrl(url);
			wechatService.update(wechat);
		} catch (IOException e) {
			return R.error("网络异常");
		}
		return R.ok();
	
			
			
	}
	
	
	
	
	

	/**
	 * 
	 * @TODO 小程序模板上传的方法
	 * @param wechatdo
	 * @return
	 */
	@ResponseBody
	@PostMapping("/save")
	public R save(@RequestParam("file") MultipartFile file, WechatDO wechatdo) {
		String URL = null;
		try {
			URL = OssUtil.fileUpload(file);
		} catch (IOException e) {
			return R.error("上传失败");
		}
		wechatdo.setUrl(URL); // 服务端
		if (wechatService.save(wechatdo) > 0) {
			return R.ok(""+wechatdo.getId()+"");
		}
		return R.error("上传失败");

	}

	/**
	 * 修改
	 */
	@ResponseBody
	@RequestMapping("/update")
	public R update(WechatDO wechatdo) {
       int update = wechatService.update(wechatdo);
       if(update == 1){
    	   return R.ok("修改成功");
		} else {
			return R.error("修改失败");
		}

	}

	/**
	 * 删除
	 */
	@PostMapping("/remove")
	@ResponseBody
	public R remove(Integer id) {
		String url = wechatService.get(id).getUrl().substring(45, 62);
		Map<String, Object> map = new HashMap<>();
		map.put("userId", id);
		List<WechatPicDO> list = picService.list(map);
		if (wechatService.remove(id) > 0 && picService.remove(id) > 0) {
			for (WechatPicDO wechatPicDO : list) {
				String picurl = wechatPicDO.getUrl().substring(45, 62);
				OssUtil.deleteBucketInfo(picurl);
			}
			OssUtil.deleteBucketInfo(url);
			return R.ok("删除成功");
		} else {
			return R.error("删除失败");
		}

	}

	/**
	 * 删除
	 */
	@PostMapping("/batchRemove")
	@ResponseBody
	@RequiresPermissions("system:wechat:batchRemove")
	public R remove(@RequestParam("ids[]") Integer[] ids) {
		wechatService.batchRemove(ids);
		return R.ok();
	}

	/**
	 * @Title: upload
	 * @Description: TODO(小程序模板多图片上传)
	 * @author: lzy
	 * @date: 2018年5月26日 上午9:53:02
	 */
	@ResponseBody
	@PostMapping("/uploads")
	R upload(@RequestParam("img") MultipartFile[] img,String id) {
		try {
			for (MultipartFile file : img) {
				String URL = null;
				try {
					URL = OssUtil.fileUpload(file);
				} catch (IOException e) {
					e.printStackTrace();
				}
				WechatPicDO picDO = new WechatPicDO();
				picDO.setUserId(Integer.parseInt(id));
				picDO.setAddTime(new Date());
				picDO.setUrl(URL);
				picService.save(picDO);

			}
		} catch (Exception e) {
			return R.error("上传失败");
		}

		return R.ok("上传成功");

	}
	
	
	

	

	/**
	 * @Title: applist
	 * @Description: TODO(移动端小程序模板详情)
	 * @author: lzy
	 * @date: 2018年5月26日 下午1:25:28
	 */
	@ResponseBody
	@GetMapping("/applist")
	public Map<String, Object> applist(@RequestParam("appId") Integer appId) {
		WechatDO wechatDO = wechatService.get(appId);
		Map<String, Object> map = new HashMap<>();
		map.put("userId", appId);
		List<WechatPicDO> list = picService.list(map);
		Map<String, Object> allmap = new HashMap<>();
		allmap.put("wechat", wechatDO);
		allmap.put("piclist", list);
 
		return allmap;

	}

	/**
	 * @Title: myCollection
	 * @Description: TODO(移动端我的收藏功能)
	 * @author: lzy
	 * @date: 2018年5月29日 上午9:13:26
	 */
	@ResponseBody
	@GetMapping("/myCollection")
	R myCollection(Integer types, Integer id) {
		UserDO user = (UserDO) SecurityUtils.getSubject().getPrincipal();
		try {
			Long userId = user.getId();
			CollectionDO collectionDO = new CollectionDO();
			collectionDO.setUserId(userId);
			collectionDO.setTypes(types);
			collectionDO.setAppId(id);
			Map<String, Object> map = new HashMap<>();
			map.put("userId", userId);
			map.put("types", types);
			map.put("appId", id);
			if (collectionService.list(map).size() > 0) {
				return R.error("已收藏");
			} else if (collectionService.save(collectionDO) == 1) {

				return R.ok("收藏成功");
			}

		} catch (Exception e) {
			return R.error("no");
		}
		return R.error("网络异常");

	}

	/**
	 * @Title: myCollection
	 * @Description: TODO(遍历我的收藏功能)
	 * @author: lzy
	 * @date: 2018年5月29日 上午9:13:26
	 */
	@ResponseBody
	@GetMapping("/myCollectionList")
	Object myCollectionList() {
		UserDO user = (UserDO) SecurityUtils.getSubject().getPrincipal();
		try {
			Long id = user.getId();
			Map<String, Object> map = new HashMap<>();
			map.put("userId", id);
			List<CollectionDO> list = collectionService.list(map);
			for (CollectionDO collectionDO : list) {
				/*
				 * 0 小程序模板 1 小程序 ； 2 广告合作 3 合作经营 4 运营商 5 商家
				 */

				if (collectionDO.getTypes() == 0) {// 小程序模板

					if (wechatService.get(collectionDO.getAppId()) != null) {
						collectionDO.setName(wechatService.get(collectionDO.getAppId()).getName());
						collectionDO.setUrl(wechatService.get(collectionDO.getAppId()).getUrl());
						collectionDO.setPrice(wechatService.get(collectionDO.getAppId()).getPrice() + "");
					} else {
						collectionDO.setName("此模板已经失效!");
						collectionDO.setUrl("");
						collectionDO.setPrice("");
					}

				} else if (collectionDO.getTypes() == 1) {// 小程序

					if (miniappDetailsService.get(collectionDO.getAppId()) != null) {
						collectionDO.setName(miniappDetailsService.get(collectionDO.getAppId()).getMiniappName());
						collectionDO.setUrl(miniappDetailsService.get(collectionDO.getAppId()).getMiniappMainImgurl());
						collectionDO
								.setPrice(miniappDetailsService.get(collectionDO.getAppId()).getMiniappMoney() + "");
					} else {
						collectionDO.setName("此小程序已经失效!");
						collectionDO.setUrl("");
						collectionDO.setPrice("");
					}

				} else if (collectionDO.getTypes() == 2) {// 广告合作
					if (advertisingService.get(collectionDO.getAppId()) != null) {
						collectionDO.setName(advertisingService.get(collectionDO.getAppId()).getAdvertisingName());
						collectionDO.setUrl(advertisingService.get(collectionDO.getAppId()).getAdvertisingMainImgurl());
						collectionDO
								.setPrice(advertisingService.get(collectionDO.getAppId()).getAdvertisingMoney() + "");
					} else {
						collectionDO.setName("此广告合作已经失效!");
						collectionDO.setUrl("");
						collectionDO.setPrice("");
					}

				} else if (collectionDO.getTypes() == 3) {// 合作经营
					if (manageService.get(collectionDO.getAppId()) != null) {
						collectionDO.setName(manageService.get(collectionDO.getAppId()).getManageName());
						collectionDO.setUrl(manageService.get(collectionDO.getAppId()).getManageMainImgurl());
						collectionDO.setPrice(manageService.get(collectionDO.getAppId()).getManageMoney() + "");
					} else {
						collectionDO.setName("此合作经营已经失效!");
						collectionDO.setUrl("");
						collectionDO.setPrice("");
					}

				} else if (collectionDO.getTypes() == 4) {// 运营商
					if (operatorService.get(collectionDO.getAppId()) != null) {
						collectionDO.setName(operatorService.get(collectionDO.getAppId()).getOperatorName());
						collectionDO.setUrl(operatorService.get(collectionDO.getAppId()).getOperatoMainImgurl());
						collectionDO.setPrice(operatorService.get(collectionDO.getAppId()).getOperatorMoney() + "");
					} else {
						collectionDO.setName("此运营商已经失效!");
						collectionDO.setUrl("");
						collectionDO.setPrice("");
					}

				} else if (collectionDO.getTypes() == 5) {// 商家
					if (merchantService.get(collectionDO.getAppId()) != null) {
						collectionDO.setName(merchantService.get(collectionDO.getAppId()).getMerchantName());
						collectionDO.setUrl(merchantService.get(collectionDO.getAppId()).getMerchantMainImgurl());
						collectionDO.setPrice(merchantService.get(collectionDO.getAppId()).getMerchantBudget() + "");
					} else {
						collectionDO.setName("此商家已经失效!");
						collectionDO.setUrl("");
						collectionDO.setPrice("");
					}

				} else {
					collectionDO.setName("收藏有误");
					collectionDO.setUrl("收藏有误");
					collectionDO.setPrice("收藏有误");
				}

			}
			return list;

		} catch (Exception e) {
			return R.error("no");
		}

	}
	
	
	//排序跳转
	@GetMapping("/sort/{id}")
	public String sort(@PathVariable("id") Integer id,Model model) {
		model.addAttribute("id", id);
		return "system/wechat/sort";
	}

	//排序更新
	@ResponseBody
	@PostMapping("/sortUpdate")
	public R sortUpdate(WechatDO wechatDO) {
		int update = wechatService.update(wechatDO);
		if(update == 1){
			return R.ok("修改成功");
		}else {
			return R.error("修改失败");
		}
		
	}

}
